package com.getpebble.android.onboarding.fragment;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.async.PblAsyncTask;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.framework.fragment.PblBaseFragment;
import com.getpebble.android.common.model.FirmwareVersion;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.common.model.FrameworkState.EventType;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.core.PblBaseActivity;
import com.getpebble.android.firmware.FirmwareUpdateCheckTask;
import com.getpebble.android.firmware.FirmwareUpdateCheckTask.Listener;
import com.getpebble.android.framework.FrameworkEventReceiver;
import com.getpebble.android.framework.FrameworkEventReceiver.IFrameworkEventListener;
import com.getpebble.android.framework.developer.PblDeviceObserver.ConnectedDeviceChangeListener;
import com.getpebble.android.framework.endpoint.InstallFirmwareEndpointSet.FirmwareInstallResult;
import com.getpebble.android.framework.firmware.FirmwareManifestBundle;
import com.getpebble.android.framework.firmware.FirmwareManifestSync;
import com.getpebble.android.framework.util.PebbleCapabilities.ConnectedDevice;
import com.getpebble.android.main.activity.MainActivity;
import com.getpebble.android.main.sections.appstore.fragment.NoConnectivityFragment;
import com.getpebble.android.onboarding.activity.OnboardingActivity;
import com.getpebble.android.util.HttpUtils;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;

public class FirmwareUpdateFragment extends PblBaseFragment {
    public static final String TAG = FirmwareUpdateFragment.class.getSimpleName();
    private TextView mBanner;
    private Button mCheckNowButton;
    private ConnectedDeviceChangeListener mConnectedDeviceChangeListener = new ConnectedDeviceChangeListener() {
        public void notifyConnectedDeviceChanged() {
            Trace.debug(FirmwareUpdateFragment.TAG, "Got connected changed message:  connected? " + (PebbleApplication.getConnectedDevice() != null));
            if (FirmwareUpdateFragment.this.mIsRebooting && PebbleApplication.getConnectedDevice() != null) {
                FirmwareUpdateFragment.this.mIsRebooting = false;
                FirmwareUpdateFragment.this.runOnUiThread(new Runnable() {
                    public void run() {
                        FirmwareUpdateFragment.this.mIsInstalling = false;
                        FirmwareUpdateFragment.this.updateUIForInstallComplete(FirmwareInstallResult.OK);
                        FirmwareUpdateFragment.this.updateFirmwareNagTime();
                        FirmwareUpdateFragment.this.mHandler.removeCallbacks(FirmwareUpdateFragment.this.mRebootTimeout);
                    }
                });
            }
        }
    };
    private IFrameworkEventListener mEventListener = new IFrameworkEventListener() {
        public void onFrameworkStateChanged(FrameworkState newState) {
            if (newState != null && newState.getLastEvent() != null) {
                if (newState.getLastEvent().equals(EventType.FIRMWARE_INSTALL_PROGRESS_CHANGED)) {
                    Trace.debug(FirmwareUpdateFragment.TAG, "Progress: " + newState.getFirmwareInstallProgress());
                    FirmwareUpdateFragment.this.mInstallProgressBar.setProgress(newState.getFirmwareInstallProgress());
                } else if (newState.getLastEvent().equals(EventType.FIRMWARE_INSTALL_STATE_CHANGED)) {
                    FirmwareInstallResult installResult = FirmwareInstallResult.fromCode(newState.getFirmwareInstallResult());
                    if (installResult.equals(FirmwareInstallResult.OK)) {
                        MobileAppBehavior.logFwUpdateComplete();
                        FirmwareUpdateFragment.this.mIsRebooting = true;
                        Activity activity = FirmwareUpdateFragment.this.getActivity();
                        if (activity instanceof OnboardingActivity) {
                            ((OnboardingActivity) activity).onReboot();
                        }
                        FirmwareUpdateFragment.this.updateUiForRebooting();
                        FirmwareUpdateFragment.this.mHandler.postDelayed(FirmwareUpdateFragment.this.mRebootTimeout, 45000);
                        return;
                    }
                    FirmwareUpdateFragment.this.mIsInstalling = false;
                    MobileAppBehavior.logFwUpdateFailed();
                    FirmwareUpdateFragment.this.updateUIForInstallComplete(installResult);
                }
            }
        }
    };
    private Runnable mFirmwareManifestSyncTimeout = new Runnable() {
        public void run() {
            Trace.warning(FirmwareUpdateFragment.TAG, "Running onFirmwareSyncComplete after timeout");
            FirmwareUpdateFragment.this.onFirmwareSyncComplete();
        }
    };
    private String mFirmwareNotes;
    private String mFirmwareUrl;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private ProgressBar mIndeterminateProgressBar;
    private ProgressBar mInstallProgressBar;
    private TextView mInstallingText;
    private boolean mIsFirmwareManifestSyncComplete = false;
    private boolean mIsFromInstallIntent = false;
    private boolean mIsFromPrfIntent = false;
    private boolean mIsInstalling = false;
    private boolean mIsOnboarding = false;
    private boolean mIsRebooting = false;
    private boolean mNeedsCheck = false;
    private Button mNotNowButton;
    private Button mPleaseWaitButton;
    private Intent mPreviousIntent = null;
    private Runnable mRebootTimeout = new Runnable() {
        public void run() {
            Trace.debug(FirmwareUpdateFragment.TAG, "Reboot should be complete");
            FirmwareUpdateFragment.this.mIsRebooting = false;
            FirmwareUpdateFragment.this.mIsInstalling = false;
            Activity activity = FirmwareUpdateFragment.this.getActivity();
            if (!FirmwareUpdateFragment.this.mIsOnboarding || activity == null) {
                FirmwareUpdateFragment.this.updateUIForInstallComplete(FirmwareInstallResult.OK);
                FirmwareUpdateFragment.this.updateFirmwareNagTime();
                return;
            }
            try {
                ((OnboardingActivity) activity).onRebootTimeout();
            } catch (IllegalStateException e) {
                Trace.error(FirmwareUpdateFragment.TAG, "Failed to switch to connection manager fragment", e);
            }
        }
    };
    private TextView mStatus;
    private ImageView mStatusImage;

    static /* synthetic */ class AnonymousClass9 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallResult = new int[FirmwareInstallResult.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallResult[FirmwareInstallResult.OK.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallResult[FirmwareInstallResult.WRONG_HW_VERSION.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallResult[FirmwareInstallResult.BUNDLE_NOT_FOUND.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallResult[FirmwareInstallResult.TIMEOUT.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallResult[FirmwareInstallResult.NO_DEVICE_CONNECTED.ordinal()] = 5;
            } catch (NoSuchFieldError e5) {
            }
        }
    }

    private class FirmwareManifestSyncTask extends PblAsyncTask {
        private FirmwareManifestSyncTask() {
        }

        public boolean doInBackground() {
            new FirmwareManifestSync(FirmwareUpdateFragment.this.getActivity()).syncForAllConnectedDevices();
            return true;
        }

        public void onTaskSuccess() {
            FirmwareUpdateFragment.this.onFirmwareSyncComplete();
        }

        public void onTaskFailed() {
        }
    }

    private void updateFirmwareNagTime() {
        PblPreferences pblPreferences = new PblPreferences(PebbleApplication.getAppContext());
        if (!isSideloading() || pblPreferences == null) {
            Trace.debug(TAG, "Not updating firmware nag time.");
            return;
        }
        Trace.debug(TAG, "Updating firmware nag time.");
        pblPreferences.setLongData(PrefKey.FIRMWARE_NAG_TIME, 0);
    }

    public int getLayoutId() {
        return R.layout.fragment_firmware_update;
    }

    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Trace.debug(TAG, "Setting up Firmware Update fragment");
        MobileAppBehavior.logScreenOpened("OnboardingSoftwareUpdate");
        this.mFirmwareNotes = getString(R.string.onboarding_updating_to_latest_firmware);
        this.mBanner = (TextView) container.findViewById(R.id.onboarding_banner);
        this.mStatusImage = (ImageView) container.findViewById(16908294);
        this.mStatus = (TextView) container.findViewById(R.id.onboarding_status);
        this.mIndeterminateProgressBar = (ProgressBar) container.findViewById(R.id.onb_check_for_updates_check_progress);
        this.mInstallProgressBar = (ProgressBar) container.findViewById(R.id.onboarding_firmware_install_progress);
        this.mInstallingText = (TextView) container.findViewById(R.id.onboarding_installing_text);
        this.mCheckNowButton = (Button) container.findViewById(R.id.onboaring_check_now_btn);
        this.mPleaseWaitButton = (Button) container.findViewById(R.id.onboarding_please_wait_btn);
        this.mNotNowButton = (Button) container.findViewById(R.id.onboarding_not_now_btn);
        FrameworkEventReceiver.registerFrameworkStateEventListener(this.mEventListener);
        PebbleApplication.addConnectedDeviceChangeListener(this.mConnectedDeviceChangeListener);
    }

    private void initForIntent(Intent intent) {
        this.mIsFromInstallIntent = true;
        this.mFirmwareNotes = intent.getStringExtra("extra_firmware_notes");
        this.mFirmwareUrl = intent.getStringExtra("extra_firmware_url");
        this.mIsFromPrfIntent = intent.getBooleanExtra("extra_prf_install", false);
        if (this.mIsFromPrfIntent) {
            initForPrf();
            initForChecking();
            return;
        }
        updateUIForChecking();
        updateUIForInstalling(null);
        startFirmwareInstall();
    }

    private void initForPrf() {
        this.mStatusImage.setImageResource(R.drawable.illustration_prf_mode);
        this.mStatus.setText(getString(R.string.onboarding_need_prf_update));
        this.mCheckNowButton.setText(getString(R.string.onboarding_need_prf_update_update_now));
    }

    public void onResume() {
        Activity activity = getActivity();
        if (activity != null) {
            Intent intent = activity.getIntent();
            if (!isInstalling() && intent != null && intent != this.mPreviousIntent) {
                if ((1048576 & intent.getFlags()) != 0) {
                    startActivity(new Intent(activity, MainActivity.class));
                    activity.finish();
                }
                Trace.debug(TAG, "Starting Sideload! (or onboarding)");
                this.mPreviousIntent = intent;
                this.mIsOnboarding = activity instanceof OnboardingActivity;
                if (isSideloading()) {
                    initForIntent(intent);
                    initForSideload();
                } else {
                    if (!this.mIsOnboarding) {
                        initForNotOnboarding();
                    }
                    initForChecking();
                }
            } else if (intent != this.mPreviousIntent) {
                Toast.makeText(activity, getString(R.string.firmware_sideload_busy), 0).show();
            }
        }
        super.onResume();
    }

    public void onStop() {
        super.onStop();
        if (!isInstalling()) {
            Activity activity = getActivity();
            if (activity == null) {
                Trace.error(TAG, "onStop: Activity was null");
            } else if (activity.getIntent() == null) {
                Trace.error(TAG, "onStop: Activity's intent was null");
            } else if (isSideloading()) {
                activity.finish();
            }
        }
    }

    private boolean isSideloading() {
        Activity activity = getActivity();
        if (activity == null) {
            return false;
        }
        Intent intent = activity.getIntent();
        if (intent == null) {
            return false;
        }
        if (intent.hasExtra("extra_firmware_url") || intent.hasExtra("extra_prf_install")) {
            return true;
        }
        return false;
    }

    private void initForNotOnboarding() {
        Trace.debug(TAG, "Not onboarding!");
        this.mNotNowButton.setVisibility(0);
        this.mNotNowButton.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                MobileAppBehavior.logButtonTapped("notNow", "OnboardingSoftwareUpdate");
                FirmwareUpdateFragment.this.goToNextScreen();
            }
        });
        this.mBanner.setVisibility(8);
    }

    private void initForSideload() {
        Trace.debug(TAG, "Sideloading");
        this.mBanner.setVisibility(8);
    }

    private void initForChecking() {
        if (ConnectedDevice.isInPrf()) {
            initForPrf();
        }
        this.mCheckNowButton.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                Activity activity = FirmwareUpdateFragment.this.getActivity();
                if (activity != null) {
                    if (HttpUtils.hasInternetConnection(activity.getApplicationContext())) {
                        MobileAppBehavior.logButtonTapped("startUpdate", "OnboardingSoftwareUpdate");
                        FirmwareUpdateFragment.this.updateUIForChecking();
                        FirmwareUpdateFragment.this.checkForUpdates();
                        return;
                    }
                    ((PblBaseActivity) activity).switchFragment(new NoConnectivityFragment(), false, false, true);
                }
            }
        });
        FirmwareManifestSyncTask syncTask = new FirmwareManifestSyncTask();
        this.mHandler.postDelayed(this.mFirmwareManifestSyncTimeout, 10000);
        syncTask.submit();
    }

    private void updateTitleText(int stringId) {
        Activity activity = getActivity();
        if (this.mIsOnboarding) {
            this.mBanner.setText(stringId);
        } else if (activity != null) {
            ActionBar actionBar = activity.getActionBar();
            if (actionBar != null) {
                actionBar.setTitle(stringId);
            }
        }
    }

    private void updateUIForChecking() {
        updateTitleText(R.string.en_onb_banner_checking_for_updates);
        this.mStatusImage.setImageResource(R.drawable.illustration_progress_cloud);
        this.mStatus.setText(R.string.text_fw_checking_in_progress);
        this.mIndeterminateProgressBar.setVisibility(0);
        this.mCheckNowButton.setText(R.string.text_please_wait);
        this.mCheckNowButton.setVisibility(8);
        this.mPleaseWaitButton.setVisibility(0);
        this.mNotNowButton.setVisibility(8);
    }

    private void updateUIForInstalling(FirmwareVersion firmwareVersion) {
        updateTitleText(R.string.en_onb_banner_updating);
        this.mStatus.setText(this.mFirmwareNotes);
        this.mIndeterminateProgressBar.setVisibility(8);
        this.mInstallProgressBar.setVisibility(0);
        this.mInstallProgressBar.setMax(100);
        if (firmwareVersion != null) {
            this.mInstallingText.setText(String.format(getString(R.string.text_installing_firmware_version), new Object[]{firmwareVersion.toString()}));
        }
        this.mInstallingText.setVisibility(0);
    }

    private void updateUiForRebooting() {
        this.mInstallProgressBar.setVisibility(8);
        this.mIndeterminateProgressBar.setVisibility(0);
        this.mInstallingText.setText(R.string.text_reconnecting);
    }

    private void updateUIForInstallComplete(FirmwareInstallResult result) {
        updateTitleText(R.string.en_onb_banner_update_complete);
        int statusResId = R.string.onboarding_firmware_unknown_error;
        switch (AnonymousClass9.$SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallResult[result.ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                this.mStatusImage.setImageResource(R.drawable.finished_checkmark);
                statusResId = R.string.onboarding_pebble_up_to_date;
                break;
            case SMTPMessage.RETURN_HDRS /*2*/:
                this.mStatusImage.setImageResource(R.drawable.illustration_info_cloud);
                statusResId = R.string.onboarding_firmware_incompatible;
                break;
            case ListInfo.INDETERMINATE /*3*/:
                this.mStatusImage.setImageResource(R.drawable.illustration_sad_cloud);
                statusResId = R.string.onboarding_firmware_not_found;
                break;
            case SMTPMessage.NOTIFY_DELAY /*4*/:
                this.mStatusImage.setImageResource(R.drawable.illustration_sad_cloud);
                statusResId = R.string.onboarding_firmware_timeout;
                break;
            case R.styleable.WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance /*5*/:
                this.mStatusImage.setImageResource(R.drawable.illustration_no_pebble_connected);
                statusResId = R.string.onboarding_firmware_no_device;
                break;
        }
        this.mStatus.setText(statusResId);
        this.mIndeterminateProgressBar.setVisibility(8);
        this.mInstallProgressBar.setVisibility(8);
        this.mInstallingText.setVisibility(8);
        this.mPleaseWaitButton.setVisibility(8);
        this.mCheckNowButton.setText(R.string.onbording_continue);
        this.mCheckNowButton.setVisibility(0);
        this.mCheckNowButton.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                MobileAppBehavior.logButtonTapped("continue", "OnboardingSoftwareUpdate");
                FirmwareUpdateFragment.this.goToNextScreen();
            }
        });
    }

    public boolean isInstalling() {
        return this.mIsInstalling || this.mIsRebooting;
    }

    private void goToNextScreen() {
        Activity activity = getActivity();
        if (activity == null) {
            Trace.debug(TAG, "Unable to continue");
        } else if (this.mIsOnboarding) {
            ((OnboardingActivity) activity).goToNextScreen();
        } else if (this.mIsFromInstallIntent) {
            Trace.debug(TAG, "Finishing activity");
            startActivity(new Intent(activity, MainActivity.class));
            activity.finish();
        } else {
            activity.onBackPressed();
        }
    }

    private synchronized void checkForUpdates() {
        Trace.debug(TAG, "Checking for updates");
        if (isFirmwareManifestSyncComplete()) {
            checkForFirmwareUpdate();
        } else {
            this.mNeedsCheck = true;
        }
    }

    private synchronized void onFirmwareSyncComplete() {
        Trace.debug(TAG, "onFirmwareSyncComplete");
        this.mHandler.removeCallbacks(this.mFirmwareManifestSyncTimeout);
        this.mIsFirmwareManifestSyncComplete = true;
        if (this.mNeedsCheck) {
            checkForFirmwareUpdate();
        }
    }

    private synchronized boolean isFirmwareManifestSyncComplete() {
        return this.mIsFirmwareManifestSyncComplete;
    }

    private void runOnUiThread(Runnable runnable) {
        Activity activity = getActivity();
        if (activity != null) {
            activity.runOnUiThread(runnable);
        }
    }

    private void checkForFirmwareUpdate() {
        Trace.debug(TAG, "Checking for firmware update");
        PblDeviceRecord deviceRecord = PebbleApplication.getConnectedDeviceRecord();
        if (deviceRecord == null) {
            updateUIForInstallComplete(FirmwareInstallResult.NO_DEVICE_CONNECTED);
        } else {
            new FirmwareUpdateCheckTask(getActivity(), deviceRecord.pblDevice, deviceRecord.fwVersion, new Listener() {
                public void onFirmwareUpdateCheckComplete(PblDevice device, final FirmwareManifestBundle bundle) {
                    if (bundle != null) {
                        Trace.debug(FirmwareUpdateFragment.TAG, "Found firmware update");
                        FirmwareUpdateFragment.this.runOnUiThread(new Runnable() {
                            public void run() {
                                FirmwareUpdateFragment.this.mFirmwareUrl = bundle.getNormalMetadata().getUrl();
                                FirmwareUpdateFragment.this.mFirmwareNotes = bundle.getNormalMetadata().getNotes();
                                FirmwareUpdateFragment.this.updateUIForInstalling(bundle.getNormalMetadata().getFriendlyVersion());
                                FirmwareUpdateFragment.this.startFirmwareInstall();
                            }
                        });
                        return;
                    }
                    Trace.debug(FirmwareUpdateFragment.TAG, "No firmware update");
                    FirmwareUpdateFragment.this.runOnUiThread(new Runnable() {
                        public void run() {
                            FirmwareUpdateFragment.this.updateUIForInstallComplete(FirmwareInstallResult.OK);
                        }
                    });
                }

                public void onInRecoveryMode(PblDevice device) {
                    FirmwareUpdateFragment.this.runOnUiThread(new Runnable() {
                        public void run() {
                            FirmwareUpdateFragment.this.updateUIForInstalling(null);
                            FirmwareUpdateFragment.this.startPrfFirmwareInstall();
                        }
                    });
                }
            }).submit();
        }
    }

    private void startFirmwareInstall() {
        Trace.debug(TAG, "Starting firmware install for " + this.mFirmwareUrl);
        this.mIsInstalling = true;
        PblDeviceRecord deviceRecord = PebbleApplication.getConnectedDeviceRecord();
        if (deviceRecord == null) {
            Trace.warning(TAG, "deviceRecord is null; not updating");
            updateUIForInstallComplete(FirmwareInstallResult.NO_DEVICE_CONNECTED);
            return;
        }
        PebbleApplication.getFrameworkInterface().updateFirmware(deviceRecord.pblDevice, Uri.parse(this.mFirmwareUrl));
    }

    private void startPrfFirmwareInstall() {
        this.mIsInstalling = true;
        PebbleApplication.getFrameworkInterface().updateFirmwareForRecovery(PebbleApplication.getConnectedDeviceRecord().pblDevice);
    }

    public void onDestroy() {
        super.onDestroy();
        FrameworkEventReceiver.unregisterFrameworkStateEventListener(this.mEventListener);
        PebbleApplication.removeConnectedDeviceChangeListener(this.mConnectedDeviceChangeListener);
        this.mHandler.removeCallbacks(this.mRebootTimeout);
    }
}
